package com.sitech.portal.system.dao.ibatis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sitech.ibnms.core.BaseIbnmsDao;
import com.sitech.ibnms.core.IPage;
import com.sitech.ibnms.core.PageForm;
import com.sitech.ibnms.util.DesEncrypterIsmp;
import com.sitech.portal.system.dao.ISysLogInmsgDao;
import com.sitech.portal.system.dao.ISysRoleDao;
import com.sitech.portal.system.dao.ISysWorkGroupDao;
import com.sitech.portal.system.domain.TblSYS_LOGINMSG;
import com.sitech.portal.system.domain.TblSYS_USER_ROLE;

public class SysLogInmsgDaoImpl extends BaseIbnmsDao implements ISysLogInmsgDao {
	
	ISysRoleDao sysRoleDao;
	ISysWorkGroupDao sysWorkGroupDao;

	public ISysRoleDao getSysRoleDao() {
		return sysRoleDao;
	}

	public void setSysRoleDao(ISysRoleDao sysRoleDao) {
		this.sysRoleDao = sysRoleDao;
	}

	public ISysWorkGroupDao getSysWorkGroupDao() {
		return sysWorkGroupDao;
	}

	public void setSysWorkGroupDao(ISysWorkGroupDao sysWorkGroupDao) {
		this.sysWorkGroupDao = sysWorkGroupDao;
	}

	public void add(TblSYS_LOGINMSG tblSYS_LOGINMSG) {
		this.insert("insertForTB_SYS_LOGINMSG", tblSYS_LOGINMSG);
	}

	public void update(TblSYS_LOGINMSG tblSYS_LOGINMSG) {
		this.update("updateForTB_SYS_LOGINMSG", tblSYS_LOGINMSG);
	}

	public void modifyTbSysLoginMsg(TblSYS_LOGINMSG tblSYS_LOGINMSG) {
		this.update("modifyTbSysLoginMsg", tblSYS_LOGINMSG);
	}
	
	public void updateMenuType(TblSYS_LOGINMSG tblSYS_LOGINMSG) {
		this.update("updateMenuType", tblSYS_LOGINMSG);
	}

	public void delete(String id[]) {
		Map map = new HashMap();

		if (id != null && id.length > 0) {
			map.put("array", id);
			this.delete("deleteForTB_SYS_LOGINMSG", map);

		}
	}

	public TblSYS_LOGINMSG findUserRoleByPk(String userId) {
		TblSYS_LOGINMSG user = new TblSYS_LOGINMSG();
		TblSYS_USER_ROLE obj = new TblSYS_USER_ROLE();
		obj.setLOGIN_ID(userId);
		List lst = sysRoleDao.findForRoleListByLonginId(obj);
		user = (TblSYS_LOGINMSG) this.querySingle(
				"findByUserCode", userId);

		user.setRoles(lst);
		
		List workGroups = sysWorkGroupDao.findWorkGroupOfUser(userId);
		user.setWorkGroups(workGroups);
		
		return user;
	}

	public List findListByMap(Map obj) {
		if (obj != null) {
			return this.query("getList", obj);
		} else {
			return this.query("getList", null);
		}
	}

	public IPage findListByDeparyType(String depart_type, String mid, PageForm pageForm) {
		TblSYS_LOGINMSG obj = new TblSYS_LOGINMSG();
		obj.setDEPT_ID(mid);
		String mySql = "";

		if (depart_type == null || depart_type.equals("")) {
			mySql = " select  a.LOGIN_ID,a.NAME ,a.USER_ID USER_ID,a.LOCAL_PHONE,a.LOGIN_PHONE,a.EMAIL_ADDR ,a.IS_VIP,b.DEPT_NAME,c.COMP_NAME "
					+ " from "
					+ " TB_SYS_LOGINMSG a,TB_SYS_DEPT b,tb_sys_company c "
					+ " where "
					+ " b.comp_id = c.comp_id and a.DEPT_ID = b.DEPT_ID(+) ";
			return this.findPage("findListByDepartALL", mySql, pageForm);
		} else if (depart_type.equals("comp") || depart_type.equals("dept")) {
			mySql = " select  a.LOGIN_ID,a.USER_ID USER_ID,a.NAME ,a.LOGIN_PHONE,a.LOCAL_PHONE,a.EMAIL_ADDR ,a.IS_VIP,b.DEPT_NAME,c.COMP_NAME "
					+ " from "
					+ " TB_SYS_LOGINMSG a,TB_SYS_DEPT b,tb_sys_company c "
					+ " where "
					+ " b.comp_id = c.comp_id and a.DEPT_ID = b.DEPT_ID AND "
					+ " a.DEPT_ID like '" + obj.getDEPT_ID() + "%' ";
			return this.findPage("findListByDepart", mySql, pageForm);
		} else {
			return null;
		}

	}

	/**
	 * 根据用户的管理单元来查询该用户有权限看到的用户列表
	 * 
	 * @param depart_type
	 * @param mid
	 * @return
	 */
	public IPage findListByDeparyTypeAndUnit(String login_id, String userName, String deptId, PageForm pageForm) {
        HashMap map = new HashMap();
        map.put("login_id",login_id);
        map.put("userName",userName);
        map.put("deptId",deptId);
		return this.findPage("findListByDepart",map,  pageForm);
	}

	@Override
	public IPage findListByDeparyTypeAndUnit(String login_id, String userName, String loginPhone, String deptId, PageForm pageForm) {
		HashMap map = new HashMap();
        map.put("login_id",login_id);
        map.put("userName",userName);
        map.put("loginPhone",loginPhone);
		map.put("deptId", deptId);
		return this.findPage("findListByDepart", map, pageForm);
	}

	public TblSYS_LOGINMSG findByUserCode(String userCode) {
		TblSYS_LOGINMSG userObj = (TblSYS_LOGINMSG) this
				.querySingle("findByUserCode", userCode);
		if (userObj != null) {
			return userObj;
		} else {
			return null;
		}
	}

	public List<HashMap> findUserByDepartId(String deptId) {
		return this.query("findTblSYS_LOGINMSGByDepartId", deptId);
	}

	/**
	 * @param userCode
	 * @param userPassword
	 * @return
	 * @throws MySecurityException
	 */
	public HashMap validLoginBySSO(String userCode, String userPassword,
			int tableCount) throws Exception {

		DesEncrypterIsmp encrypter = new DesEncrypterIsmp();

		if (null == userCode || "".equals(userCode))
			throw new Exception("请输入用户名！");

		HashMap map = null;
//		if (tableCount == 2) {
			map = this.findUserinfo(userCode);
//		} else {
//			map = this.findUserinfoNoManageUnit(userCode);
//		}
		if (null == map) {
			throw new Exception(userCode + " 用户不存在");
		}
		/*
		 * if (!encrypter.encrypt(userPassword).equalsIgnoreCase((String)
		 * (map.get("LOGIN_PASSWD")==null?"":map.get("LOGIN_PASSWD")))){ throw
		 * new MySecurityException("密码不正确! 用户:" + userCode); }
		 */
		if (TblSYS_LOGINMSG.USER_IS_UNVALID.equals(Short.valueOf((String) map
				.get("LOCKSTATE")))) {
			throw new Exception("用户被锁定! 用户:" + userCode);
		}

		return map;

	}

	/**
	 * @param userCode
	 *            用户名
	 * @param userPassword
	 *            密码
	 * @param tableCount
	 *            表数量(用户特权表和管理单元表)
	 * @return
	 * @throws MySecurityException
	 */
	public HashMap validLogin(String userCode, String userPassword,
			int tableCount) throws Exception {

		DesEncrypterIsmp encrypter = new DesEncrypterIsmp();

		if (null == userCode || "".equals(userCode))
			throw new Exception("请输入用户名！");

		HashMap map = null;
		if (tableCount == 2) {// 存在用户特权表和管理单元表
			map = this.findUserinfo(userCode);
		} else {
			map = this.findUserinfoNoManageUnit(userCode);
		}
		if (null == map) {
			throw new Exception(userCode + " 用户不存在");
		}
		if (!encrypter.encrypt(userPassword).equalsIgnoreCase(
				(String) (map.get("LOGIN_PASSWD") == null ? "" : map
						.get("LOGIN_PASSWD")))) {
			throw new Exception("密码不正确! 用户:" + userCode);
		}
		if (TblSYS_LOGINMSG.USER_IS_UNVALID.equals(Short.valueOf((String) map
				.get("LOCKSTATE")))) {
			throw new Exception("用户被锁定! 用户:" + userCode);
		}

		return map;

	}

	public int getCount(String condition) {
		Integer i = null;
		i = (Integer) this.querySingle(
				"findForTB_SYS_LOGINMSGbyCount", null);
		return i.intValue();
	}

	public int getCountModule(java.util.HashMap a) {
		return Integer.parseInt(this.querySingle(
					"getCountModule", a).toString());
	}

	public List getNaviParam(List getNaviParam) {

		return this.query("getNaviParam", getNaviParam);
	}

	/**
	 * update password
	 */
	public void updatePassword(java.util.HashMap a) {
		this.update("updatePasswordForTB_SYS_LOGINMSG", a);
	}

	/**
	 * frozen user
	 */
	public void frozenUser(String id[]) {
		if (id != null && id.length > 0) {
			for (int i = 0; i < id.length; i++) {
				this.update("forzenUserForTB_SYS_LOGINMSG", id[i]);
			}
		}
	}

	/**
	 * cancel frozen user
	 */
	public void cancelfrozen(String id[]) {
		if (id != null && id.length > 0) {
			for (int i = 0; i < id.length; i++) {
				this.update("cancelUserForTB_SYS_LOGINMSG", id[i]);
			}
		}
	}

	/**
	 * show all users don't been frozen
	 */
	public IPage findUnfrozenList(HashMap map,PageForm pageForm) {

		return this.findPage("findUnfrozenForTB_SYS_LOGINMSG",map,
				pageForm);
	}

	/**
	 * show all users have been frozen
	 */
	public IPage findFrozenList(HashMap map,PageForm pageForm) {

		return this.findPage("findFrozenForTB_SYS_LOGINMSG",map,
				pageForm);
	}

	public List findUserAll() {
		List userList = this.query("findUserAll", null);
		if (userList != null) {
			return userList;
		} else {
			return null;
		}
	}

	public HashMap findUserinfo(String userCode) {
		return (HashMap) this.querySingle("findUserInfo",
					userCode);
	}

	public HashMap findUserinfoNoManageUnit(String userCode) {
		return (HashMap) this.querySingle(
					"findUserInfoNoManageUnit", userCode);
	}

	public IPage findUserCodeLike(String usercode, String name, PageForm pageForm) {

		String sql = " select * from TB_SYS_LOGINMSG where 1=1";

		if (usercode != null && !"".equals(usercode)) {
			sql += " and login_id like '%" + usercode + "%'";
		}

		if (name != null && !"".equals(name)) {
			sql += " and name like '%" + name + "%'";
		}
		return this.findPage("findUserCodeLike", sql, pageForm);
	}

	/*
	 * 获取工作组和人的树形结构
	 */
	public List loadLoginTreeList(String WORKGROUP_ID, String flag) {
		// String sql = " SELECT a.DEPT_ID AS VALUE, a.DEPT_NAME AS NAME,
		// a.SUPER_DEPT_ID AS super_conf_id FROM TB_SYS_DEPT a " +
		// " WHERE a.dept_id IN (SELECT a.dept_id FROM tb_sys_loginmsg a,
		// tb_sys_user_workgroup b WHERE a.login_id = b.login_id AND
		// b.workgroup_id = '"+WORKGROUP_ID+"')" +
		// " UNION ALL SELECT a.login_id AS VALUE, a.NAME, a.DEPT_ID AS
		// super_conf_id" +
		// " FROM tb_sys_loginmsg a, tb_sys_user_workgroup b WHERE a.login_id =
		// b.login_id AND b.workgroup_id = '"+WORKGROUP_ID+"'";

		String sql = "";

		if ("1".equals(flag)) {

			sql = "SELECT a.dept_id AS VALUE, a.dept_name AS NAME,                            "
					+ "       a.super_dept_id AS super_conf_id                                    "
					+ "  FROM tb_sys_dept a                                                       "
					+ " WHERE a.dept_id IN (                                                      "
					+ "          SELECT super_dept_id                                             "
					+ "            FROM tb_sys_dept                                               "
					+ "           WHERE dept_id IN (                                              "
					+ "                    SELECT super_dept_id                                   "
					+ "                      FROM tb_sys_dept                                     "
					+ "                     WHERE dept_id IN (                                    "
					+ "                              SELECT a.dept_id AS dept_id                  "
					+ "                                FROM tb_sys_loginmsg a,                    "
					+ "                                     tb_sys_user_workgroup b               "
					+ "                               WHERE a.login_id = b.login_id               "
					+ "                                 AND b.workgroup_id = '"
					+ WORKGROUP_ID
					+ "')             "
					+ "                    UNION                                                  "
					+ "                    SELECT a.dept_id AS dept_id                            "
					+ "                      FROM tb_sys_loginmsg a, tb_sys_user_workgroup b      "
					+ "                     WHERE a.login_id = b.login_id                         "
					+ "                           AND b.workgroup_id = '"
					+ WORKGROUP_ID
					+ "')                   "
					+ "          UNION                                                            "
					+ "          SELECT super_dept_id                                             "
					+ "            FROM tb_sys_dept                                               "
					+ "           WHERE dept_id IN (                                              "
					+ "                    SELECT a.dept_id AS dept_id                            "
					+ "                      FROM tb_sys_loginmsg a, tb_sys_user_workgroup b      "
					+ "                     WHERE a.login_id = b.login_id                         "
					+ "                           AND b.workgroup_id = '"
					+ WORKGROUP_ID
					+ "')                   "
					+ "          UNION                                                            "
					+ "          SELECT a.dept_id AS dept_id                                      "
					+ "            FROM tb_sys_loginmsg a, tb_sys_user_workgroup b                "
					+ "           WHERE a.login_id = b.login_id AND b.workgroup_id = '"
					+ WORKGROUP_ID
					+ "')     "
					+ "UNION ALL                                                                  "
					+ "SELECT a.login_id AS VALUE, a.NAME, a.dept_id AS super_conf_id             "
					+ "  FROM tb_sys_loginmsg a, tb_sys_user_workgroup b                          "
					+ " WHERE a.login_id = b.login_id AND b.workgroup_id = '"
					+ WORKGROUP_ID + "'                ";

		} else if ("2".equals(flag)) {

			// 按部门查询的检查人的树SQL
			sql = "SELECT s.dept_id AS VALUE,s.dept_name AS NAME,s.super_dept_id AS super_conf_id FROM tb_sys_dept s start with  s.dept_id = '"
					+ WORKGROUP_ID
					+ "' connect by prior s.dept_id = s.super_dept_id"
					+ " UNION ALL"
					+ " SELECT a.login_id AS VALUE, a.NAME, a.dept_id AS super_conf_id from tb_sys_loginmsg a where a.dept_id in  (SELECT s.dept_id  FROM tb_sys_dept s  start with  s.dept_id = '"
					+ WORKGROUP_ID
					+ "' connect by prior s.dept_id = s.super_dept_id)"
					+ " UNION "
					+ "SELECT s.dept_id AS VALUE,s.dept_name AS NAME,s.super_dept_id AS super_conf_id FROM tb_sys_dept s start with s.dept_id = '"
					+ WORKGROUP_ID
					+ "' connect by prior s.super_dept_id = s.dept_id";

		} else if ("3".equals(flag)) {
			sql = "select a.login_id as VALUE,a.name as NAME,a.dept_id as super_conf_id "
					+ " from TB_SYS_loginmsg a where login_id in(select b.login_id from Tb_Sys_User_Role b where b.role_id = '"
					+ WORKGROUP_ID
					+ "')"
					+ "union all "
					+ "SELECT s.dept_id  as VALUE,s.dept_name AS NAME,s.super_dept_id AS super_conf_id FROM tb_sys_dept s where s.dept_id in (select c.dept_id "
					+ "from TB_SYS_loginmsg c where login_id in (select d.login_id from Tb_Sys_User_Role d where d.role_id = '"
					+ WORKGROUP_ID
					+ "'))"
					+ "union "
					+ "select g.dept_id AS VALUE,g.dept_name AS NAME,g.super_dept_id AS super_conf_id from (SELECT distinct "
					+ "s.super_dept_id AS super_conf_id FROM tb_sys_dept s where s.dept_id in (select c.dept_id from TB_SYS_loginmsg c "
					+ "where login_id in(select d.login_id from Tb_Sys_User_Role d where d.role_id = '"
					+ WORKGROUP_ID
					+ "'))) aa,tb_sys_dept g where aa.super_conf_id=g.dept_id";
		} else {
			System.out.println("判断按部门或工作组指派查询处理人的标志位错误！");
		}
		System.out.println("检查人树SQL" + sql);
		return this.query("loadLoginTreeList", sql);
	}

	public IPage selectUserByPage(PageForm pageForm) {
		return this.findPage("getUserByPage", new HashMap<String,Object>(), pageForm);
	}
}
